"""
catsup v1.0

Usage:
    catsup fahuo [-s <file>|--settings=<file>] [-l <level>|--level=<level>] [-m <mll>|--mll=<mll>]
    catsup check_order [-s <file>|--settings=<file>] [-l <level>|--level=<level>]
    catsup update_cookies [-s <file>|--settings=<file>] [-l <level>|--level=<level>]
    catsup update_cookies_with_passwd [-s <file>|--settings=<file>] [-l <level>|--level=<level>] [-a <account>|--account=<account>]
    catsup -h | --help
    catsup --version

Options:
    -h --help               show this screen.
    -s --settings=<file>    specify a config file. [default: ./fahuo.toml]
    -l --level=<level>      日志登记 10 为debug 20 为info
    -m --mll=<mll>      model

"""
import json
import logging
import os
import time
import traceback

from parguments import Parguments
from config import cfg

from fahuo import Fahuo
from http_service import get_send_orders, upload_used_codes, get_sended_orders, update_orders, get_cookies

parguments = Parguments(__doc__, version='1.0')
logging.basicConfig(level=20,
                    format='%(filename)s - %(lineno)s - %(asctime)s - %(levelname)s- %(message)s - %(funcName)s')


@parguments.command
def update_cookies(settings, level):
    """
        Usage:
        catsup update_cookies [-s <file>|--settings=<file>] [-l <level>|--level=<level>]

        Options:
            -h --help               show this screen.
            -l --level=<level>      日志登记 10 为debug 20 为info [default: 20]
            -s --settings=<file>    specify a config file. [default: ./fahuo.toml]
        """
    init(settings, level)
    logging.info("更新cookies")
    while True:
        try:
            cookies = get_cookies()
            if len(cookies) == 0:
                logging.error("http res is empty")
            for name in cookies:
                co = cookies[name]
                file_object = open(cfg["cookie_path"] + name + '_cookie.json', mode="w")
                try:
                    file_object.write(json.dumps(co))
                    logging.info(f"{name} 更新成功")
                finally:
                    file_object.close()

        except Exception as e:
            logging.error(traceback.format_exc())
        time.sleep(10 * 60)


@parguments.command
def update_cookies_with_passwd(settings, level, account):
    """
        Usage:
        catsup update_cookies_with_passwd [-s <file>|--settings=<file>] [-l <level>|--level=<level>] [-a <account>|--account=<account>]

        Options:
            -h --help               show this screen.
            -l --level=<level>      日志登记 10 为debug 20 为info [default: 20]
            -s --settings=<file>    specify a config file. [default: ./fahuo.toml]
            -a --account=<account>    specify a account
        """
    init(settings, level)
    logging.info("update_cookies_with_passwd")
    while True:
        items = cfg["accounts"].items()
        try:
            for k in items:
                name = k[1]["name"]
                if account is not None and name != account:
                    logging.info(f"{account} {name} continue")
                    continue
                index = k[1]["index"]
                f = Fahuo(cfg["chrome_path"], cfg["cookie_path"], name,
                          cfg["hidden_chrome"], [], index)
                if f.login() is True:
                    logging.info(f"{name} cookie有效不更新")
                    f.quit()
                    continue
                if f.save_cookies_with_passwd(cfg["account"], cfg["passwd"]) is True:
                    f.quit()
                    logging.info(f"{name} 更新cookie成功")
                    continue
                f.quit()
                logging.error(f"{name}更新cookie失败")

        except Exception as e:
            logging.error(traceback.format_exc())
        time.sleep(30 * 60)


@parguments.command
def check_order(settings, level):
    """
        Usage:
        catsup check_order [-s <file>|--settings=<file>] [-l <level>|--level=<level>]

        Options:
            -h --help               show this screen.
            -l --level=<level>      日志登记 10 为debug 20 为info [default: 20]
            -s --settings=<file>    specify a config file. [default: ./fahuo.toml]
        """
    init(settings, level)
    logging.info("抖音自动检测发货情况")
    while True:
        try:
            for s in cfg["accounts"]:
                s = cfg["accounts"][s]["name"]
                orders = get_sended_orders(s)
                if orders is False or len(orders) == 0:
                    logging.warning(f"{s} 已发货未检测数据为空")
                    continue
                logging.info(f"{s} 需要检测的数据为{orders}")
                f = Fahuo(cfg["chrome_path"], cfg["cookie_path"], s, cfg["hidden_chrome"])
                if f.login() is False:
                    logging.error(f"{s} 登录失败")
                    f.quit()
                    continue
                result = f.batch_check_fahuo_status(orders)
                logging.info(f"{s} 需要检测结果为{result}")

                f.quit()
                if len(result) > 0:
                    update_orders(result)
        except Exception:
            logging.error(traceback.format_exc())

        time.sleep(60)


@parguments.command
def fahuo(settings, level, mll):
    """
        Usage:
        catsup fahuo [-s <file>|--settings=<file>] [-l <level>|--level=<level>] [-m <mll>|--mll=<mll>]

        Options:
            -h --help               show this screen.
            -l --level=<level>      日志登记 10 为debug 20 为info [default: 20]
            -s --settings=<file>    specify a config file. [default: ./fahuo.toml]
            -m --mll=<mll>      this
        """
    init(settings, level)
    logging.info("抖音发货启动")
    save_pid(cfg['fahuo_pid_file'])
    while True:
        try:
            pay_time_begin = time.time() - cfg["pay_begin_days"] * 86400
            pay_time_end = time.time() - cfg["pay_end_hours"] * 3600
            logging.info("pay begin date " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(pay_time_begin)))
            logging.info("pay end date " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(pay_time_end)))
            for s in cfg["accounts"]:
                s = cfg["accounts"][s]["name"]
                send_orders = get_send_orders(s, pay_time_begin, pay_time_end)
                f = None
                if len(send_orders) > 0:
                    f = Fahuo(cfg["chrome_path"], cfg["cookie_path"], s, cfg["hidden_chrome"], cfg["ignore_products"])
                    if f.login() is False:
                        f.quit()
                        logging.info(s + "登录失败")
                        continue

                while len(send_orders) > 0:
                    logging.info(s + ",".join(str(i) for i in send_orders))
                    send_result, yc_codes, ignore_codes = f.batch_fahuo(send_orders, True)
                    if send_result is False:
                        f.quit()
                        logging.info(s + " send result is empty")
                        break
                    logging.info(s + "send result " + ''.join(str(i) for i in send_result))
                    logging.info(s + "yc result " + ''.join(str(i) for i in yc_codes))
                    upload_used_codes(send_result, "success")
                    upload_used_codes(yc_codes, "yc")
                    upload_used_codes(ignore_codes, "ignore")
                    send_orders = get_send_orders(s, pay_time_begin, pay_time_end)

                logging.warning(f"无可发货订单{s}")

                if f is not None:
                    f.quit()




        except Exception as e:
            logging.error(traceback.format_exc())
        time.sleep(60)


def init(settings, level):
    cfg.load(settings)
    logging.basicConfig(level=int(level), format='%(filename)s - %(lineno)s - %(asctime)s - %(levelname)s- %(message)s')


def save_pid(file):
    f = open(file, 'w+')
    try:
        f.write(str(os.getpid()))
    finally:
        f.close()


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    parguments.run()
